package com.example.chongwushangcheng.util;

import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * RecyclerView网格布局间距装饰器
 */
public class ItemSpaceDecoration extends RecyclerView.ItemDecoration {

    private int spanCount; // 列数
    private int spacing; // 间距
    private boolean includeEdge; // 是否包含边缘

    /**
     * 构造函数
     *
     * @param spanCount   列数
     * @param spacing     间距（像素）
     * @param includeEdge 是否包含边缘
     */
    public ItemSpaceDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int column = position % spanCount;

        if (includeEdge) {
            // 外边缘也有间距
            outRect.left = spacing - column * spacing / spanCount;
            outRect.right = (column + 1) * spacing / spanCount;

            if (position < spanCount) {
                outRect.top = spacing;
            }
            outRect.bottom = spacing;
        } else {
            // 只有内部有间距
            outRect.left = column * spacing / spanCount;
            outRect.right = spacing - (column + 1) * spacing / spanCount;
            if (position >= spanCount) {
                outRect.top = spacing;
            }
        }
    }
} 